
from flask import Flask
from flask import jsonify
from flask import abort
from flask import make_response
from flask import request
from flask_script import Manager

app = Flask(__name__)
app.debug = True
manager = Manager(app)

tasks = [
  {
    'id': 1,
    'title': 'Bug ',
    'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
    'one': False
  },
  {
    'id': 2,
    'title': 'Bug ',
    'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
    'one': False
  }
]

@app.route('/')
def index():
  return 'hello Flask Restful!'

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
  return jsonify({'tasks': tasks})

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
  task = filter(lambda t: t['id'] == task_id, tasks)
  if len(task) == 0:
    abort(404)
  return jsonify({'task': task})

@app.errorhandler(404)
def not_found(error):
  return make_response(jsonify({'error': 'Not found'}), 404)

@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
  if not request.json or not 'title' in request.json:
    abort(400)
  task = {
    'id': tasks[-1]['id'] + 1,
    'title': request.json['title'],
    'description': request.json.get('description', ""),
    'done': False
  }
  tasks.append(task)
  return jsonify({'task': task}), 201

@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
  task = filter(lambda t: t['id'] == task_id, tasks)
  if len(task) == 0:
    abort(404)
  if not request.json:
    abort(400)
  if 'title' in request.json and type(request.json['title']) is not unicode :
    abort(400)
  if 'done' in request.json and type(request.json['done']) is not unicode :
    abort(400)
  task[0]['title'] = request.json.get('title', taks[0]['title'])
  task[0]['description'] = request.json.get('description', taks[0]['description'])
  task[0]['done'] = request.json.get('done', taks[0]['done'])
  return jsonify({'task': task[0]})

if __name__ == '__main__':
  manager.run()


